<template>
  <div class="workflow">
    <el-row>

      <!-- 头部1 -->
      <el-col :span="24">
        <div>
          <!-- 包一层卡片 -->
          <el-card class="workflow-head-card" shadow="never" :body-style=" {padding:'10px'}">
            <!--el-row包着el-col不容易出bug-->
            <el-row>
              <!-- 命名空间的下拉框 -->
              <el-col :span="6">
                <div>
                  <span>命名空间: </span>
                  <!-- 下拉框 -->
                  <!-- filterable：带搜索功能 -->
                  <!-- placeholder 默认提示 -->
                  <!-- label 显示内容 -->
                  <!-- value 绑定到v-model的值中 -->
                  <el-select v-model="namespaceValue" filterable placeholder="请选择">
                    <el-option
                        v-for="(item, index) in namespaceList"
                        :key="index"
                        :label="item.metadata.name"
                        :value="item.metadata.name">
                    </el-option>
                  </el-select>
                </div>
              </el-col>
              <!-- 刷新按钮 -->
              <!--span占两个格子，offset是指前边空出多少个格子-->
              <el-col :span="2" :offset="16">
                <div>
                  <!-- 每次刷新，都重新调一次list接口，刷新表格中的数据 -->
                  <el-button style="border-radius:2px;" icon="Refresh" plain>刷新</el-button>
                </div>
              </el-col>
            </el-row>
          </el-card>
        </div>
      </el-col>

      <!-- header2 步骤条 -->
      <el-col :span="24">
        <div>
          <!-- 步骤条展示，active属性控制到了哪一步 -->
          <el-card class="workflow-head-card" shadow="never" :body-style="{padding:'30px 10px 20px 10px'}">
            <el-steps :active="active" align-center finish-status="success">
              <el-step title="步骤1" description="选择工作流类型, ClusterIP NodePort Workflow"></el-step>
              <el-step title="步骤2" description="填写Deployment Workflow Workflow表单"></el-step>
              <el-step title="步骤3" description="创建Deployment Workflow Workflow"></el-step>
            </el-steps>
          </el-card>
        </div>
      </el-col>

      <!-- 头部3 -->
      <el-col :span="24">
        <div>
          <!-- 包一层卡片 -->
          <el-card class="workflow-head-card" shadow="never" :body-style=" {padding:'10px'}">
            <el-row>
              <!-- 创建按钮 -->
              <el-col :span="2">
                <div>
                  <!-- 创建工作流 -->
                  <!-- createWorkflowDrawerIndex1-》
                  createWorkflowDrawerIndex2-1-》createWorkflowDrawerIndex2-2 -->
                  <el-button
                      style="border-radius:2px;"
                      icon="Edit"
                      type="primary"
                      @click="createWorkflowDrawerIndex1 = true"
                      v-loading.fullscreen.lock="fullscreenLoading">
                    创建工作流
                  </el-button>
                </div>
              </el-col>
              <!-- 搜索框和搜索按钮 -->
              <el-col :span="6">
                <div>
                  <el-input class="workflow-head-search" clearable placeholder="请输入" v-model="searchInput"></el-input>
                  <el-button style="border-radius:2px;" icon="Search" type="primary" plain @click="getWorkflows()">搜索</el-button>
                </div>
              </el-col>
            </el-row>
          </el-card>
        </div>
      </el-col>

      <!-- 数据表格 -->
      <el-col :span="24">
        <div>
          <!-- 包一层卡片 -->
          <el-card class="workflow-body-card" shadow="never" :body-style=" {padding:'5px'}">
            <!-- 数据表格 -->
            <!-- v-loading用于加载时的loading动画 -->
            <el-table
                style="width:100%;font-size:12px;margin-bottom:10px;"
                :data="workflowList"
                v-loading="appLoading"
                :row-key="getRowKeys"
                :expand-row-keys="expandKeys"
                @expand-change="expandChange">
              <!-- 最左侧留出20px的宽度，更加没关 -->
              <el-table-column width="20"></el-table-column>


              <el-table-column min-width="50" align=left label="ID" prop="id"></el-table-column>
              <el-table-column min-width="100" label="Workflow名">
                <template v-slot="scope">
                  <a class="workflow-body-workflowname">{{ scope.row.name }}</a>
                </template>
              </el-table-column>
              <el-table-column label="类型" prop="type">
                <template v-slot="scope">
                  <el-tag type="warning">{{ scope.row.type }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="实例数" prop="replicas"></el-table-column>
              <el-table-column min-width="100" label="deployment" prop="deployment"></el-table-column>
            <el-table-column min-width="150" label="service" prop="service"></el-table-column>
            <el-table-column min-width="150" label="ingress" prop="ingress"></el-table-column>
            <el-table-column align=center min-width="150" label="创建时间">
              <template v-slot="scope">
                <el-tag type="info">{{ timeTransNot8(scope.row.created_at) }} </el-tag>
              </template>
            </el-table-column>
            <el-table-column align=center label="操作" width="400">
              <template v-slot="scope">
                <el-button size="small" style="border-radius:2px;" icon="Delete" type="danger" @click="handleConfirm(scope, '删除', delWorkflow)">删除 </el-button>
              </template>
            </el-table-column>

            </el-table>
            <!-- 分页配置 -->
            <!-- background 背景色灰 -->
            <!-- size-change 单页大小改变后触发 -->
            <!-- current-change 页数改变后触发 -->
            <!-- current-page 当前页 -->
            <!-- page-size 单页大小 -->
            <!-- layout 分页器支持的功能 -->
            <!-- total 数据总条数 -->
            <el-pagination
                class="workflow-body-pagination"
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="pagesizeList"
                :page-size="pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="workflowTotal">
            </el-pagination>
          </el-card>
        </div>
      </el-col>

    </el-row>



    <!--展示YAML信息的弹框-->
    <el-dialog title="YAML信息" v-model="yamlDialog" width="45%" top="2%">
      <!-- codemirror编辑器 -->
      <!-- border 带边框 -->
      <!-- options 编辑器配置 -->
      <!-- change 编辑器中的内容变化时触发 -->
      <codemirror
          :value="contentYaml"
          border
          :options="cmOptions"
          height="500"
          style="font-size:14px;"
          @change="onChange" >
      </codemirror>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="yamlDialog = false">取 消</el-button>
        <el-button type="primary" @click="updateWorkflow()">更 新</el-button>
      </span>
      </template>
    </el-dialog>

    <!-- 抽屉弹框1 -->
    <el-drawer
        v-model="createWorkflowDrawerIndex1"
        :direction="direction"
        :before-close="handleClose">
      <template #title>
        <h4>创建Workflow-步骤1</h4>
      </template>
      <template #default>
        <el-row type="flex" justify="center">
          <el-col :span="20">
            <el-form label-width="80px">
              <el-form-item class="workflow-create-form" label="类型"
                            prop="name">
                <el-radio v-model="createWorkflow.type"
                          label="ClusterIP">ClusterIP</el-radio>
                <el-radio v-model="createWorkflow.type"
                          label="NodePort">NodePort</el-radio>
                <el-radio v-model="createWorkflow.type"
                          label="Ingress">Ingress</el-radio>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </template>
      <template #footer>
        <el-button @click="drawerCancel('createWorkflowDrawerIndex1')">取消</el-button>
          <el-button type="primary" @click="workflowIndex1Next()">下一步</el-button>
      </template>
    </el-drawer>

    <!-- 抽屉弹框2 -->
    <el-drawer
        v-model="createWorkflowDrawerIndex2_1"
        :direction="direction"
        :before-close="handleClose">
      <template #title>
        <h4>创建Workflow-步骤2</h4>
      </template>
      <template #default>
        <el-row type="flex" justify="center">
          <el-col :span="20">
            <el-form ref="createWorkflow" :rules="createWorkflowRules" :model="createWorkflow" label-width="80px">
              <h4 style="margin-bottom:10px">Deployment</h4>
              <el-form-item class="workflow-create-form" label="名称" prop="name">
                <el-input v-model="createWorkflow.name"></el-input>
              </el-form-item>
              <el-form-item class="workflow-create-form" label="命名空间" prop="namespace">
                <el-select v-model="createWorkflow.namespace" filterable placeholder="请选择">
                  <el-option
                      v-for="(item, index) in namespaceList"
                      :key="index"
                      :label="item.metadata.name"
                      :value="item.metadata.name">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item class="workflow-create-form" label="副本数" prop="replicas">
                <el-input-number v-model="createWorkflow.replicas" :min="1" :max="10"></el-input-number>
                <el-popover
                    placement="top"
                    :width="100"
                    trigger="hover"
                    content="申请副本数上限为10个">
                  <template #reference>
                    <el-icon style="width:2em;font-size:18px;color:#4795EE"><WarningFilled/></el-icon>
                  </template>
                </el-popover>
              </el-form-item>
              <el-form-item class="workflow-create-form" label="镜像" prop="image">
                <el-input v-model="createWorkflow.image"></el-input>
              </el-form-item>
              <el-form-item class="workflow-create-form" label="标签" prop="label_str">
                <el-input v-model="createWorkflow.label_str" placeholder="示例: project=ms,app=gateway"></el-input>
              </el-form-item>
              <el-form-item class="workflow-create-form" label="资源配额" prop="resource">
                <el-select v-model="createWorkflow.resource" placeholder="请选择">
                  <el-option value="0.5/1" label="0.5C1G"></el-option>
                  <el-option value="1/2" label="1C2G"></el-option>
                  <el-option value="2/4" label="2C4G"></el-option>
                  <el-option value="4/8" label="4C8G"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item class="workflow-create-form" label="容器端口" prop="container_port">
                <el-input v-model="createWorkflow.container_port" placeholder="示例: 80"></el-input>
              </el-form-item>
              <el-form-item class="workflow-create-form" label="健康检查" prop="health">
                <el-switch v-model="createWorkflow.health_check" />
              </el-form-item>
              <el-form-item class="workflow-create-form" label="检查路径" prop="healthPath">
                <el-input v-model="createWorkflow.health_path" placeholder="示例: /health"></el-input>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </template>
      <template #footer>
        <el-button @click="drawerCancel('createWorkflowDrawerIndex2_1')">取消</el-button>
          <el-button type="primary" @click="submitForm('createWorkflow',workflowIndex2_1Next)">下一步</el-button>
      </template>
    </el-drawer>

    <!-- 抽屉弹框3 -->
    <el-drawer
        v-model="createWorkflowDrawerIndex2_2"
        :direction="direction"
        :before-close="handleClose">
      <template #title>
        <h4>创建Workflow-步骤2</h4>
      </template>
      <template #default>
        <el-row type="flex" justify="center">
          <el-col :span="20">
            <el-form ref="createWorkflow" :rules="createWorkflowRules" :model="createWorkflow" label-width="80px">
              <h4 style="margin-bottom:10px">Service</h4>
              <el-form-item class="service-create-form" label="Service端口" prop="port">
                <el-input v-model="createWorkflow.port" placeholder="示例:80"></el-input>
              </el-form-item>
              <el-form-item v-if="createWorkflow.type == 'NodePort'" class="service-create-form" label="NodePort" prop="node_port">
                <el-input v-model="createWorkflow.node_port" placeholder="示例: 30001"></el-input>
              </el-form-item>
              <el-divider v-if="createWorkflow.type == 'Ingress'"></el-divider>
                <h4 v-if="createWorkflow.type == 'Ingress'" style="margin-bottom:10px">Ingress</h4>
                <el-form-item v-if="createWorkflow.type == 'Ingress'" class="deploy-create-form" label="域名" prop="host">
                  <el-input v-model="createWorkflow.host" placeholder="示例:www.example.com"></el-input>
                </el-form-item>
                <el-form-item v-if="createWorkflow.type == 'Ingress'" class="ingress-create-form" label="Path" prop="path">
                  <el-input v-model="createWorkflow.path" placeholder="示例:/abc"></el-input>
                </el-form-item>
                <el-form-item v-if="createWorkflow.type == 'Ingress'" class="deploy-create-form" label="匹配类型" prop="path_type">
                  <el-select v-model="createWorkflow.path_type" placeholder="请选择">
                    <el-option value="Prefix" label="Prefix"></el-option>
                    <el-option value="Exact" label="Exact"></el-option>
                    <el-option value="ImplementationSpecific" label="ImplementationSpecific"></el-option>
                  </el-select>
                </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </template>
      <template #footer>
        <el-button @click="drawerCancel('createWorkflowDrawerIndex2_2')">取消</el-button>
          <el-button type="primary" @click="submitForm('createWorkflow',createWorkflowFunc)">立即创建</el-button>
      </template>
    </el-drawer>

  </div>
</template>
<script>
import common from "../common/Config";
import httpClient from '../../utils/request';

import yaml2obj from 'js-yaml';
import json2yaml from 'json2yaml';//需要npm install json2yaml

//引入xterm终端依赖
import { Terminal } from 'xterm';
import { FitAddon } from 'xterm-addon-fit';
import 'xterm/css/xterm.css';
import 'xterm/lib/xterm.js';

export default {
  data() {
    return {
      //命名空间
      namespaceValue: 'default',
      namespaceList: [],
      namespaceListUrl: common.k8sNamespaceList,

      //头部工具二部分
      //搜索框内容
      searchInput: '',


      //分页
      currentPage: 1,
      pagesize: 10,
      pagesizeList: [10, 20, 30],
      //列表
      appLoading: false,
      workflowList: [],
      workflowTotal: 0,
      getWorkflowsData: {
        url: common.k8sWorkflowList,
        params: {
          filter_name: '',
          namespace: '',
          page: 1,
          limit: 10,
        }
      },

      //编辑器配置
      cmOptions: common.cmOptions,
      contentYaml: '',
      //详情
      workflowDetail: {},
      getWorkflowDetailData: {
        url: common.k8sWorkflowDetail,
        params: {
          workflow_name: '',
          namespace: ''
        }
      },
      //yaml更新
      yamlDialog: false,
      updateWorkflowData: {
        url: common.k8sWorkflowUpdate,
        params: {
          namespace: '',
          content: ''
        }
      },


      //删除
      delWorkflowData: {
        url: common.k8sWorkflowDel,
        params: {
          id: -1,
        }
      },

      //expand扩展
      //tab栏
      activeName: 'container',
      //展开和关闭
      expandKeys: [],
      //标记打开和关闭，用于workflow名
      expandMap: {},

      //日志
      //获取容器
      containerList: {},
      containerValue: '',
      getWorkflowContainerData: {
        url: common.k8sWorkflowContainer,
        params: {
          workflow_name: '',
          namespace: ''
        }
      },
      //获取日志
      logContent: '',
      getWorkflowLogData: {
        url: common.k8sWorkflowLog,
        params: {
          container_name: '',
          workflow_name: '',
          namespace: ''
        }
      },

      //terminal
      term: null,
      socket: null,

      //工作流以及3个抽屉弹出框
      active: 0,
      createWorkflowDrawerIndex1: false,
      createWorkflowDrawerIndex2_1: false,
      createWorkflowDrawerIndex2_2: false,

      //创建
      fullscreenLoading: false,
      direction: 'rtl',
      createWorkflow: {
        name: '',
        namespace: '',
        replicas: 1,
        image: '',
        resource: '',
        health_check: false,
        health_path: '',
        label_str: '',
        label: {},
        container_port: '',
        type: '',
        port: '',
        node_port: '',
        host: '',
        path: '',
        path_type: ''
      },

      createWorkflowData: {
        url: common.k8sWorkflowCreate,
        params: {}
      },

      createWorkflowRules: {
        name: [{
          required: true,
          message: '请填写名称',
          trigger: 'change'
        }],
        image: [{
          required: true,
          message: '请填写镜像',
          trigger: 'change'
        }],
        namespace: [{
          required: true,
          message: '请选择命名空间',
          trigger: 'change'
        }],
        resource: [{
          required: true,
          message: '请选择配额',
          trigger: 'change'
        }],
        label_str: [{
          required: true,
          message: '请填写标签',
          trigger: 'change'
        }],
        container_port: [{
          required: true,
          message: '请填写容器端口',
          trigger: 'change'
        }],
        type: [{
          required: true,
          message: '请填写工作流类型',
          trigger: 'change'
        }],
        port: [{
          required: true,
          message: '请填写Workflow端口',
          trigger: 'change'
        }],
        node_port: [{
          required: true,
          message: '请填写NodePort',
          trigger: 'change'
        }],
        host: [{
          required: true,
          message: '请填写域名',
          trigger: 'change'
        }],
        path: [{
          required: true,
          message: '请填写路径',
          trigger: 'change'
        }],
        path_type: [{
          required: true,
          message: '你选择匹配类型',
          trigger: 'change'
        }],
      },



    }
  },
  methods: {
    //获取Namespace列表
    getNamespaces() {
      httpClient.get(this.namespaceListUrl)
          .then(res => {
            this.namespaceList = res.data.items
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
    },

    //头部工具二部分
    //处理抽屉的关闭，增加体验感
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(() => {
            done();
          })
          .catch(() => {});
    },


    //页面大小发生变化时触发，赋值并重新获取列表
    handleSizeChange(size) {
      this.pagesize = size;
      this.getWorkflows()
    },
    //页数发生变化时触发，复制并重新获取列表
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.getWorkflows()
    },
    //字符串截取、拼接并返回
    ellipsis(value) {
      return value.length>15?value.substring(0,15)+'...':value
    },
    //格林威治时间转为北京时间
    timeTrans(timestamp) {
      let date = new Date(new Date(timestamp).getTime() + 8 * 3600 * 1000)
      date = date.toJSON();
      date = date.substring(0, 19).replace('T', ' ')
      return date
    },
    //获取Workflow列表
    getWorkflows() {
      //表格加载动画开启
      this.appLoading = true
      //getWorkflowsData是用于发起workflow列表请求的专用的对象，里面有url和params参 数,以下是赋值
      this.getWorkflowsData.params.filter_name = this.searchInput
      this.getWorkflowsData.params.namespace = this.namespaceValue
      this.getWorkflowsData.params.page = this.currentPage
      this.getWorkflowsData.params.limit = this.pagesize
      httpClient.get(this.getWorkflowsData.url, {params: this.getWorkflowsData.params})
          .then(res => {
            //响应成功，获取workflow列表和total
            this.workflowList = res.data.items
            this.workflowTotal = res.data.total
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
      //加载动画关闭
      this.appLoading = false
    },

    //json转yaml方法
    transYaml(content) {
      return json2yaml.stringify(content)
    },
    //yaml转对象
    transObj(content) {
      return yaml2obj.load(content)
    },
    //编辑器内容变化时触发的方式,用于将更新的内容复制到变量中
    onChange(val) {
      this.contentYaml = val
    },
    //获取workflow详情，e参数标识传入的scope插槽，.row是该行的数据
    getWorkflowDetail(e) {
      this.getWorkflowDetailData.params.workflow_name = e.row.metadata.name
      this.getWorkflowDetailData.params.namespace = this.namespaceValue
      httpClient.get(this.getWorkflowDetailData.url, {params: this.getWorkflowDetailData.params})
          .then(res => {
            //响应成功，获得workflow详情
            this.workflowDetail = res.data
            //将对象转成yaml格式的字符串
            this.contentYaml = this.transYaml(this.workflowDetail)
            //打开弹出框
            this.yamlDialog = true
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
    },
    //更新workflow
    updateWorkflow() {
      //将yaml格式的workflow对象转为json
      let content = JSON.stringify(this.transObj(this.contentYaml))
      this.updateWorkflowData.params.namespace = this.namespaceValue
      this.updateWorkflowData.params.content = content
      httpClient.put(this.updateWorkflowData.url, this.updateWorkflowData.params)
          .then(res => {
            this.$message.success({
              message: res.msg
            })
            //更新后重新获取列表
            this.getWorkflows()
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
      //关闭弹出框
      this.yamlDialog = false
    },




    //弹出确认框，用于危险操作的double check
    //obj是行数据，opeateName是操作名，fn是操作的方法
    handleConfirm(obj, operateName, fn) {
      this.confirmContent = '确认继续 ' + operateName + ' 操作吗？'
      //$confirm用于弹出确认框
      this.$confirm(this.confirmContent,'提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
          .then(() => {
            //restartWorkflow(e)或者delWorkflow(e)
            fn(obj)
          })
          .catch(() => {
            this.$message.info({
              message: '已取消操作'
            })
          })
    },

    //删除workflow
    delWorkflow(e) {
      this.delWorkflowData.params.id = e.row.id
      httpClient.delete(this.delWorkflowData.url, {data: this.delWorkflowData.params})
          .then(res => {
            this.$message.success({
              message: res.msg
            })
            this.getWorkflows()
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
    },

    //计算重启次数
    restartTotal(e) {
      let index, sum = 0
      let containerStatuses = e.row.status.containerStatuses
      for ( index in containerStatuses) {
        sum = sum + containerStatuses[index].restartCount
      }
      return sum
    },

    //展开和关闭
    getRowKeys(row) {
      return row.name
    },
    //row，展开的当前行的数据
    //expandedRows，展开的所有行的数据组成的数组，但是这里用法是只会有一行，也就是数组长度永远 为1
    expandChange(row, expandedRows) {
      //初始化变量
      //清空expandKeys，代表关闭所有展开的行
      this.expandKeys = []
      //清空日志内容
      this.logContent= ''
      //清空containervalue，展开时不显示上次的值
      this.containerValue = ''
      //将tab标签页顶部页面调成容器
      this.activeName = 'container'

      //expandedRows.length == 1表示展开，expandedRows.length == 0 表示关闭
      if (expandedRows.length > 0) {
        //expandMap key表示展开过的行的key，值为1表示展开标记，值为0表示关闭标记
        //expandMap用于数据表格点击name的展开，用于判断这一行是展开还是关闭的行为
        this.expandMap[row.metadata.name] = 1
        //将expandMap除了row.metadata.name，其他key的值都置为0
        this.setExpandMap(row.metadata.name)
        //这里才是真正的展开，将row.metadata.name添加到expandKeys数组中展开，然后执行方 法获取container
        this.expandKeys.push(row.metadata.name)
        this.getWorkflowContainer(row)
      } else {
        //关闭标记
        this.expandMap[row.metadata.name] = 0
      }

      // //判断是展开还是关闭
      // if (expandedRows.length > 0) {
      //   this.expandKeys.push(row.metadata.name)
      // }

    },
    //匹配expandMap中workflowName，不相等的全都置为0，意为除了workflowName这行，其他全都标记关闭
    setExpandMap(workflowName) {
      let key
      for ( key in this.expandMap ) {
        key !== workflowName ? this.expandMap[key] = 0 : ''
      }
    },

    getWorkflowContainer(row) {
      this.getWorkflowContainerData.params.workflow_name = row.metadata.name
      this.getWorkflowContainerData.params.namespace = this.namespaceValue
      httpClient.get(this.getWorkflowContainerData.url, {params:
        this.getWorkflowContainerData.params})
          .then(res => {
            this.containerList = res.data
            this.containerValue = this.containerList[0]
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
    },
    getWorkflowLog(workflowName) {
      this.getWorkflowLogData.params.workflow_name = workflowName
      this.getWorkflowLogData.params.container_name = this.containerValue
      this.getWorkflowLogData.params.namespace = this.namespaceValue
      httpClient.get(this.getWorkflowLogData.url, {params:
        this.getWorkflowLogData.params})
          .then(res => {
            this.logContent = res.data
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
    },


    //terminal
    initTerm() {
      //初始化xterm实例
      this.term = new Terminal({
        rendererType: 'canvas', //渲染类型
        rows: 30, //行数
        cols: 110,
        convertEol: false, //启用时，光标将设置为下一行的开头
        scrollback: 10, //终端中的回滚量
        disableStdin: false, //是否应禁用输入
        cursorStyle: 'underline', //光标样式
        cursorBlink: true, //光标闪烁
        theme: {
          foreground: 'white', //字体
          background: '#060101', //背景色
          cursor: 'help' //设置光标
        }
      });
      //绑定dom
      this.term.open(document.getElementById('xterm'))
      //终端适应父元素大小
      const fitAddon = new FitAddon()
      this.term.loadAddon(fitAddon)
      fitAddon.fit();
      //获取终端的焦点
      this.term.focus();
      let _this = this; //一定要重新定义一个this，不然this指向会出问题
      //onData方法用于定义输入的动作
      this.term.onData(function (key) {
        // 这里key值是输入的值，数据格式就是后端定义的
        //{"operation":"stdin","data":"ls"}
        let msgOrder = {
          operation: 'stdin',
          data: key,
        };
        //发送数据,string转json
        _this.socket.send(JSON.stringify(msgOrder));
      });
      //发送resize请求
      let msgOrder2 = {
        operation: 'resize',
        cols: this.term.cols,
        rows: this.term.rows,
      };
      this.socket.send(JSON.stringify(msgOrder2))
    },
    //初始化websocket
    initSocket(row) {
      //定义websocket连接地址
      let terminalWsUrl = common.k8sTerminalWs + "?workflow_name=" +
          row.metadata.name + "&container_name=" + this.containerValue + "&namespace=" +
          this.namespaceValue
      //实例化
      this.socket = new WebSocket(terminalWsUrl);
      //关闭连接时的方法
      this.socketOnClose();
      //建立连接时的方法
      this.socketOnOpen();
      //接收消息的方法
      this.socketOnMessage();
      //报错时的方法
      this.socketOnError();
    },
    socketOnOpen() {
      this.socket.onopen = () => {
        //简历连接成功后，初始化虚拟终端
        this.initTerm()
      }
    },
    socketOnMessage() {
      this.socket.onmessage = (msg) => {
        //接收到消息后将字符串转为对象，输出data内容
        let content = JSON.parse(msg.data)
        this.term.write(content.data)
      }
    },
    socketOnClose() {
      this.socket.onclose = () => {
        //关闭连接后打印在终端里
        this.term.write("链接已关闭")
      }
    },
    socketOnError() {
      this.socket.onerror = () => {
        console.log('socket 链接失败')
      }
    },
    //关闭连接
    closeSocket() {
      //若没有实例化，则不需要关闭
      if (this.socket === null) {
        return
      }
      this.term.write("链接关闭中。。。")
      this.socket.close()
    },

    //转换时间
    timeTransNot8(timestamp) {
      let date = new Date(new Date(timestamp).getTime() + 8 * 3600 * 1000)
      date = date.toJSON();
      date = date.substring(0, 19).replace('T', ' ')
      return date
    },

    //关闭抽屉
    drawerCancel(drawerName) {
      switch (drawerName) {
        case 'createWorkflowDrawerIndex1':
          this.createWorkflowDrawerIndex1 = false
          break
        case 'createWorkflowDrawerIndex2_1':
          this.createWorkflowDrawerIndex2_1 = false
          break
        case 'createWorkflowDrawerIndex2_2':
          this.createWorkflowDrawerIndex2_2 = false
      }
      this.active = 0
    },
    //抽屉1的提交
    workflowIndex1Next() {
      //判断是否选择了type
      if (!this.createWorkflow.type) {
        this.$message.warning({
          message: "请选择工作流类型"
        })
        return
      }
      //关闭抽屉1
      this.createWorkflowDrawerIndex1 = false
      //打开抽屉2_1
      this.createWorkflowDrawerIndex2_1 = true
      //步骤条完成第一步
      this.active = 1
    },

    //抽屉2_2提交
    submitForm(formName, fn) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          fn()
        } else {
          return false;
        }
      })
    },
    //抽屉2的提交
    workflowIndex2_1Next() {
      //关闭抽屉2_1
      this.createWorkflowDrawerIndex2_1 = false
      //打开抽屉2_2
      this.createWorkflowDrawerIndex2_2 = true
    },

    //真正的创建workflow的方法
    createWorkflowFunc() {
      //验证标签,如果不符合a=b,c=d的格式，咱返回
      let reg = new RegExp("(^[A-Za-z]+=[A-Za-z0-9]+).*")
      if (!reg.test(this.createWorkflow.label_str)) {
        this.$message.warning({
          message: "标签填写异常，请确认后重新填写"
        })
        return
      }
      //加载动画开启
      this.fullscreenLoading = true
      //处理标签,将标签转成map a=b -> map[a]=b
      let label = new Map()
      let cpu, memory
      let a = (this.createWorkflow.label_str).split(",")
      a.forEach(item => {
        let b = item.split("=")
        label[b[0]] = b[1]
      })
      //处理配额
      let resourceList = this.createWorkflow.resource.split("/")
      cpu = resourceList[0]
      memory = resourceList[1] + "Gi"
      //处理其他参数
      this.createWorkflowData.params = this.createWorkflow
      this.createWorkflowData.params.label = label
      this.createWorkflowData.params.cpu = cpu
      this.createWorkflowData.params.memory = memory
      this.createWorkflowData.params.container_port =
          parseInt(this.createWorkflow.container_port)
      this.createWorkflowData.params.port = parseInt(this.createWorkflow.port)
      this.createWorkflowData.params.node_port =
          parseInt(this.createWorkflow.node_port)
      //处理Hosts及httppath，跟后端处理相同，将数据转成map[host]=httpPaths的格式
      if (this.createWorkflow.type == 'Ingress') {
        let hosts = new Map()
        let httpPaths = []
        let httpPath = {
          path: this.createWorkflow.path,
          path_type: this.createWorkflow.path_type,
          service_name: this.createWorkflow.name,
          service_port: parseInt(this.createWorkflow.port)
        }
        httpPaths.push(httpPath)
        hosts[this.createWorkflow.host] = httpPaths
        this.createWorkflowData.params.hosts = hosts
      }
      //发送请求
      httpClient.post(this.createWorkflowData.url,
          this.createWorkflowData.params)
          .then(res => {
            this.$message.success({
              message: res.msg
            })
            this.getWorkflows()
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
      this.resetForm('createWorkflow')
      this.createWorkflowDrawerIndex2_2 = false
      this.active = 3
      //fullscreenLoading其实无作用 建议用v-loading
      this.fullscreenLoading = false
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }

  },
  watch: {
    //监听namespace的值,若发生变化，则执行handler方法中的内容
    namespaceValue: {
      handler() {
        //将namespace的值存入本地，用于path切换时依旧能获取得到
        localStorage.setItem('namespace', this.namespaceValue)

        //重置当前页为1
        this.currentPage = 1
        //获取workflow列表
        this.getWorkflows()
      }
    },

    //若tab标签页切到日志，则重新加载日志内容
    activeName: {
      handler() {
        if ( this.activeName == 'log' ) {
          this.expandKeys.length == 1 ? this.getWorkflowLog(this.expandKeys[0]) :''
        }
      }
    }

  },
  beforeMount() {
    //加载页面时先获取localStorage中的namespace值，若获取不到则默认default
    if (localStorage.getItem('namespace') !== undefined && localStorage.getItem('namespace') !== null) {
      this.namespaceValue = localStorage.getItem('namespace')
    }
    this.getNamespaces()
    this.getWorkflows()



  },



}
</script>
<style scoped>
/* 卡片属性 */
.workflow-head-card,.workflow-body-card {
  border-radius: 1px;
  margin-bottom: 5px;
}

/*头部工具2部分*/
/* 卡片属性 */
.workflow-head-card,.workflow-body-card {
  border-radius: 1px;
  margin-bottom: 5px;
}
/* 搜索框 */
.workflow-head-search {
  width:160px;
  margin-right:10px;
}

/*数据表格*/
/* 数据表格workflow名颜色 */
.workflow-body-workflowname {
  color: #4795EE;
}
/* workflow名鼠标悬停 */
.workflow-body-workflowname:hover {
  color: rgb(84, 138, 238);
  cursor: pointer;
  font-weight: bold;
}

/* workflow状态栏圆点的css实现 */
.success-dot{
  display:inline-block;
  width: 7px;
  height:7px;
  background: rgb(27, 202, 21);
  border-radius:50%;
  border:1px solid rgb(27, 202, 21);
  margin-right: 10px;
}
.warning-dot{
  display:inline-block;
  width: 7px;
  height:7px;
  background: rgb(233, 200, 16);
  border-radius:50%;
  border:1px solid rgb(233, 200, 16);
  margin-right: 10px;
}
.error-dot{
  display:inline-block;
  width: 7px;
  height:7px;
  background: rgb(226, 23, 23);
  border-radius:50%;
  border:1px solid rgb(226, 23, 23);
  margin-right: 10px;
}
.success-status {
  color: rgb(27, 202, 21);
}
.warning-status {
  color: rgb(233, 200, 16);
}
.error-status {
  color: rgb(226, 23, 23);
}

/deep/ .el-tabs__item {
  font-size: 12px;
}
/deep/ .el-tabs__header {
  margin-bottom: 8px;
}

/*容器日志*/
.workflow-body-log-card, .workflow-body-shell-card {
  border-radius:1px;
  height:600px;
  overflow:auto;
  background-color: #060101;
}
.workflow-body-log-card {
  color: aliceblue;
}
.workflow-body-log-span {
  white-space:pre;
}

/deep/ .el-drawer__header {
  margin-bottom: 0px !important;
}
/deep/ .el-drawer__body {
  padding: 0px 0px 0px 0px;
}

</style>